<?php


namespace app\zyhsapi\lib\good_rtc_live;


use app\chat\LiveMessage;
use app\common\lib\Util;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveMedia;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveMessage;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLivePlayRecord;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveRecord;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveUserRecord;
use app\zyhsapi\service\CacheZyhs;
use think\Db;
use think\Log;
use think\queue\Job;

class GoodRtcLiveJob
{
    /**
     * 记录直播间用户信息
     * @param Job $job
     * @param $jobData
     */
    public function userLoginOrOutTask(Job $job, $jobData)
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
            return;
        }
        // $jobData = [
        //     'app_type_num' => '',   // 1=>准有好事 || 2=>准了
        //     'type' => '',   // login || login_out
        //     'uid' => '',
        //     'live_record_id' => '',
        //     'login_time' => '',
        //     'duration' => '',
        //     'login_out_time' => '',
        // ];
        try
        {
            if ($jobData['type'] === 'login')
            {
                $res = (new ZyhsGoodRtcLiveUserRecord())->where(['app_type' => $jobData['app_type_num'], 'uid' => $jobData['uid'], 'live_record_id' => $jobData['live_record_id'], 'login_time' => $jobData['login_time']])->count();
                if (!$res)
                {
                    $d = [
                        'app_type' => $jobData['app_type_num'],
                        'uid' => $jobData['uid'],
                        'live_record_id' => $jobData['live_record_id'],
                        'duration' => 0,
                        'login_time' => $jobData['login_time'],
                        'login_out_time' => 0,
                    ];

                    (new ZyhsGoodRtcLiveUserRecord())->insert($d);
                }
            } else
            {
                $id = (new ZyhsGoodRtcLiveUserRecord())->where(['app_type' => $jobData['app_type_num'], 'uid' => $jobData['uid'], 'live_record_id' => $jobData['live_record_id'], 'login_time' => $jobData['login_time']])->value('id');
                if ($id)
                {   // 更新记录 用户在线时长
                    (new ZyhsGoodRtcLiveUserRecord())->where(['id' => $id])->update(['duration' => $jobData['duration'], 'login_out_time' => $jobData['login_out_time']]);
                } else
                {
                    $d = [
                        'app_type' => $jobData['app_type_num'],
                        'uid' => $jobData['uid'],
                        'live_record_id' => $jobData['live_record_id'],
                        'duration' => $jobData['duration'],
                        'login_time' => $jobData['login_time'],
                        'login_out_time' => $jobData['login_out_time'],
                    ];
                    // 写入用户在线时长 信息
                    (new ZyhsGoodRtcLiveUserRecord())->insert($d);
                }
            }
        }
        catch (\Exception $e)
        {
            Log::write("准有好事 优质连线 直播间用户进入或登出记录失败，数据「" . json_encode($jobData, JSON_UNESCAPED_UNICODE) . "」：错误消息：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
        }

        $job->delete();
    }

    /**
     * 更新播放媒体音频信息
     * @param Job $job
     * @param $jobData
     */
    public function changeMediaAudioTask(Job $job, $jobData)
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
            return;
        }
        try
        {
            // $jobData = [
            //     'live_record_id' => ''
            // ];
            $nowTime = time();
            $zyhsGoodRtcLiveRecordModel = new ZyhsGoodRtcLiveRecord();
            $zyhsGoodRtcLiveMediaModel = new ZyhsGoodRtcLiveMedia();

            $recordInfo = $zyhsGoodRtcLiveRecordModel->getInfoById($jobData['live_record_id']);
            if ($recordInfo['status'] !== 1)
            {   // 直播已结束
                $job->delete();
                return;
            }
            if ($recordInfo['current_mid'])
            {
                // 当前播放的音频数据信息
                $currentMediaInfo = $zyhsGoodRtcLiveMediaModel->getInfoById($recordInfo['current_mid'], ['duration']);
                $dT = $nowTime - $recordInfo['start_play_time'] > $currentMediaInfo['duration'] - 1;
            } else
            {
                $currentMediaInfo = null;
                $dT = true;
            }
            if ($dT)
            {   // 切换下一个音频
                // 获取下一个音频数据
                $mids = $zyhsGoodRtcLiveMediaModel->where('status = 1')->order('sort desc,id asc')->column('id');
                if ($recordInfo['current_mid'])
                {
                    $n = array_search($recordInfo['current_mid'], $mids);
                    $n++;
                    if ($n >= count($mids))
                    {
                        $n = 0;
                    }
                } else
                {
                    $n = 0;
                }
                // 下一个音频数据信息
                $nextMid = $mids[$n];
                $zyhsGoodRtcLiveRecordModel->UpdateData($jobData['live_record_id'], [
                    'current_mid' => $nextMid,
                    'start_play_time' => $nowTime,
                ]);
                // 添加 媒体播放记录
                (new ZyhsGoodRtcLivePlayRecord())->insert([
                    'live_record_id' => $jobData['live_record_id'],
                    'mid' => $nextMid,
                    'create_time' => $nowTime,
                ]);
                // 添加 发送虚拟弹幕队列信息
                $nextMediaInfo = $zyhsGoodRtcLiveMediaModel->getInfoById($nextMid, ['bullet_chat', 'extend', 'duration']);
                $extend = $nextMediaInfo['extend'] ? json_decode($nextMediaInfo['extend'], true) : [];
                $timerBullet = $extend['timer_bullet'] ?? [];
                $msgList = [];
                $bulletChatList = $nextMediaInfo['bullet_chat'] ? explode("\n", $nextMediaInfo['bullet_chat']) : [];
                foreach ($bulletChatList as $bulletChatItem)
                {
                    $ml = explode('；', $bulletChatItem);
                    $uid = mt_rand(10000, 10499);
                    foreach ($ml as $item)
                    {
                        $msgList[] = [
                            'uid' => $uid,
                            'msg' => $item,
                        ];
                    }
                }
                $num = count($msgList);
                $delay = (int)($nextMediaInfo['duration'] / ($num + 2));
                // 发送气氛弹幕
                foreach ($msgList as $k => $msgItem)
                {
                    Util::queuePush('zyhs_good_rtc_live_vrtualuser_user_send_msg', [
                        'live_record_id' => $jobData['live_record_id'],
                        'msg' => $msgItem['msg'],
                        'vid' => $msgItem['uid'],
                        'mid' => $nextMid,
                    ], $delay * ($k + 1));
                }
                // 发送 定时弹幕
                foreach ($timerBullet as $timerBulletItem)
                {
                    $uid = mt_rand(10000, 10499);
                    Util::queuePush('zyhs_good_rtc_live_vrtualuser_user_send_msg', [
                        'live_record_id' => $jobData['live_record_id'],
                        'msg' => $timerBulletItem['content'],
                        'vid' => $uid,
                        'mid' => $nextMid,
                    ], (int)$timerBulletItem['time']);
                }
                // 下次切换队列添加
                Util::queuePush('zyhs_good_rtc_live_change_media_audio', $jobData, (int)$nextMediaInfo['duration']);
            } else
            {   // 继续当前音频 并 添加延迟切换队列
                Util::queuePush('zyhs_good_rtc_live_change_media_audio', $jobData, $currentMediaInfo['duration'] - ($nowTime - $recordInfo['start_play_time']));
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }

        $job->delete();
    }

    /**
     * 发送虚拟用户弹幕
     * @param Job $job
     * @param $jobData
     */
    public function vrtualuserUserSendMsgTask(Job $job, $jobData)
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
            return;
        }
        // $jobData = [
        //     'live_record_id' => '',
        //     'vid' => '', // 虚拟用户uid
        //     'mid' => '', // 发送弹幕时播放音频数据信息ID
        //     'msg' => '', // 虚拟用户发送的弹幕
        // ];
        try
        {
            $zyhsGoodRtcLiveRecordModel = new ZyhsGoodRtcLiveRecord();
            // 虚拟弹幕数增加
            $zyhsGoodRtcLiveRecordModel->where(['id' => $jobData['live_record_id']])->update(['msg_num2' => Db::raw('msg_num2 + 1')]);
            $userInfo = Db::table('good_wechat.zyhs_vrtualuser_user')->where(['id' => $jobData['vid']])->find();
            $id = (new ZyhsGoodRtcLiveMessage())->insertGetId([
                'app_type' => 0,    // 0=>准有好事虚拟用户 1=>准有好事APP 2=>准了APP
                'uid' => $jobData['vid'],
                'type' => 2,
                'live_record_id' => $jobData['live_record_id'],
                'mid' => $jobData['mid'],
                'content' => $jobData['msg'],
                'create_time' => time(),
            ]);
            // 发送 发送虚拟用户弹幕
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_GOOD_RTC_LIVE_ROOM, 0, $jobData['live_record_id']), LiveMessage::MSG_TYPE_POP_GOOD_RTC_LIVE_MSG, [
                'user_info' => [
                    'uen' => '',    // 虚拟用户 uen为空
                    'name' => $userInfo['nickname'] ?? '温柔的雨',
                ],
                'msg_info' => [
                    'id' => (int)$id,
                    'color' => '#ffffff',
                    'content' => $jobData['msg'],
                ],
            ]);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }

        $job->delete();
    }

    /**
     * 发送用户在线人数
     * @param Job $job
     * @param $jobData
     * @return void
     */
    public function sendUserOnlineNum(Job $job, $jobData)
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
            return;
        }
        // $jobData = [
        //     'live_record_id' => ''
        // ];
        try
        {
            $zyhsGoodRtcLiveRecordModel = new ZyhsGoodRtcLiveRecord();
            $recordInfo = $zyhsGoodRtcLiveRecordModel->getInfoById($jobData['live_record_id']);
            // 获取 在线人数
            $onlineNum = $zyhsGoodRtcLiveRecordModel->getOnlineNum($jobData['live_record_id']);
            // 增加 基础虚拟人数
            $onlineNum = $onlineNum + $recordInfo['base_num'];
            //  发送 用户在线人数信息
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_GOOD_RTC_LIVE_ROOM, 0, $jobData['live_record_id']), LiveMessage::MSG_TYPE_GOOD_RTC_LIVE_ONLINE_MSG, '在线：' . $onlineNum);
            //  删除 同步在线人数缓存
            CacheZyhs::rm('good_rtc_live:sync_online_num:' . $jobData['live_record_id']);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }

        $job->delete();
    }
}
